import ProxyConfig from "@/../config/proxy"

export default new (class {
  //获取数据Host
  requestHost(key: keyof typeof ProxyConfig) {
    return process.env.NODE_ENV === "production" ? this.getHost(key) : key
  }

  //获取HOST
  getHost(key: keyof typeof ProxyConfig): string {
    const checkUrl = new URL(location.href)
    let newUrl: string = ""
    if (checkUrl.searchParams.has(key)) {
      newUrl = checkUrl.searchParams.get(key).toString()
    }
    return newUrl || ProxyConfig[key][API_ENV || "test"]
  }
  //返回处理后的URL
  replaceHost(url: string, key: keyof typeof ProxyConfig) {
    if (!url) return ""
    const urls = url.split("?")
    const [realUrl, urlParams] = urls
    const filePath = realUrl.includes("http")
      ? new URL(realUrl).pathname
      : realUrl.startsWith("//")
      ? new URL("http:" + realUrl).pathname
      : realUrl.startsWith("/")
      ? realUrl
      : `/${realUrl}`
    const host = this.getHost(key)
    return host + filePath + (!!urlParams ? "?" + urlParams : "")
  }
})()
